<template>
  <el-dialog
    v-model="visible"
    :title="isEditMode ? '编辑智能体' : '注册智能体'"
    width="600px"
    :before-close="handleClose"
    class="register-dialog"
    append-to-body
    destroy-on-close
    :close-on-press-escape="true"
    @keydown.esc="handleClose"
  >
    <div class="dialog-content">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="register-form"
        @submit.prevent="handleSubmit"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          
          <el-form-item label="智能体名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入智能体名称，长度在2-50个字符之间"
              show-word-limit
              clearable
            />
          </el-form-item>

          <el-form-item label="描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              placeholder="请输入智能体描述，长度在10-200个字符之间"
              :rows="3"
              show-word-limit
              resize="none"
            />
          </el-form-item>

          <el-form-item label="作者" prop="author">
            <el-input
              v-model="form.author"
              placeholder="请输入作者名称，长度在2-30个字符之间"
              maxlength="30"
              clearable
            />
          </el-form-item>

          <el-form-item label="版本" prop="version">
            <el-input
              v-model="form.version"
              placeholder="例如: 1.0.0，版本号格式为 x.x.x"
              maxlength="20"
              clearable
            />
          </el-form-item>
        </div>

        <!-- 分类和标签 -->
        <div class="form-section">
          <h3 class="section-title">分类标签</h3>
          
          <el-form-item label="分类" prop="category">
            <el-select
              v-model="form.category"
              placeholder="请选择分类"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="category in categories"
                :key="category.value"
                :label="category.label"
                :value="category.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="标签" prop="tags">
            <el-select
              v-model="form.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择或输入标签"
              style="width: 100%"
            >
              <el-option
                v-for="tag in availableTags"
                :key="tag"
                :label="tag"
                :value="tag"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 配置信息 -->
        <div class="form-section">
          <h3 class="section-title">配置信息</h3>
          
          <el-form-item label="分享链接" prop="shareUrl">
            <el-input
              v-model="form.shareUrl"
              placeholder="请输入智能体分享链接地址"
              clearable
            />
          </el-form-item>

          <el-form-item label="使用说明" prop="usage">
            <el-input
              v-model="form.usage"
              type="textarea"
              placeholder="请输入使用说明"
              :rows="3"
              show-word-limit
              resize="none"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" class="cancel-btn">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="loading"
          class="submit-btn"
        >
          {{ loading ? (isEditMode ? '更新中...' : '注册中...') : (isEditMode ? '更新智能体' : '注册智能体') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import type { CreateAgentInput, EditAgentInput } from '@/types/agent'
import { AGENT_CATEGORIES } from '@/lib/dict-constant'
import { animateDialogEnter, animateDialogExit, animateButtonClick } from '@/services/animationService'

// 组件属性
interface Props {
  modelValue: boolean
  agent?: any // 编辑模式时传入的智能体数据
}

// 组件事件
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', data: CreateAgentInput): void
  (e: 'edit', data: EditAgentInput): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const form = reactive<CreateAgentInput>({
  name: '',
  description: '',
  author: '',
  version: '1.0.0',
  category: '',
  tags: [],
  shareUrl: '',
  config: '',
  usage: ''
})

// 分类选项（使用统一的字典常量）
const categories = AGENT_CATEGORIES

// 可用标签
const availableTags = [
  'AI助手', '自动化', '效率工具', '创意', '学习',
  '办公', '编程', '写作', '分析', '设计',
  '教育', '娱乐', '工具', '实用', '创新'
]

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入智能体名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度应在2-50个字符之间', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入智能体描述', trigger: 'blur' },
    { min: 10, max: 200, message: '描述长度应在10-200个字符之间', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者名称', trigger: 'blur' },
    { min: 2, max: 30, message: '作者名称长度应在2-30个字符之间', trigger: 'blur' }
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' },
    { pattern: /^\d+\.\d+\.\d+$/, message: '版本号格式应为 x.x.x', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  shareUrl: [
    { required: true, message: '请输入分享链接', trigger: 'blur' },
    { validator: validateUrl, trigger: 'blur' }
  ],
  config: [
    { validator: validateUrl, trigger: 'blur' }
  ]
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit('update:modelValue', value)
})

// 是否为编辑模式
const isEditMode = computed(() => !!props.agent)

// 监听弹窗显示状态
watch(visible, async (newVal) => {
  if (newVal) {
    await nextTick()
    animateDialogEnter('.register-dialog .el-dialog')
    // 添加键盘事件监听
    document.addEventListener('keydown', handleKeydown)
    
    // 如果是编辑模式，预填充表单数据；否则重置表单
    if (isEditMode.value && props.agent) {
      fillFormWithAgentData(props.agent)
    } else {
      // 非编辑模式下重置表单，确保每次添加智能体时表单为空
      resetForm()
    }
  } else {
    // 移除键盘事件监听
    document.removeEventListener('keydown', handleKeydown)
  }
})

/**
 * 处理键盘事件
 */
function handleKeydown(event: KeyboardEvent) {
  if (event.key === 'Escape' && visible.value) {
    handleClose()
  }
}

/**
 * 验证URL地址是否有效
 */
function validateUrl(rule: any, value: string, callback: any) {
  // 如果值为空，则跳过验证（因为config字段是可选的）
  if (!value || value.trim() === '') {
    callback()
    return
  }
  
  try {
    new URL(value)
    callback()
  } catch (error) {
    callback(new Error('请输入有效的URL地址'))
  }
}

/**
 * 预填充表单数据（编辑模式）
 */
function fillFormWithAgentData(agent: any) {
  Object.assign(form, {
    name: agent.name || '',
    description: agent.description || '',
    author: agent.author || '',
    version: agent.version || '1.0.0',
    category: agent.category || '',
    tags: agent.tags || [],
    shareUrl: agent.shareUrl || '',
    config: agent.config || '',
    usage: agent.usage || ''
  })
  
  formRef.value?.clearValidate()
}

/**
 * 重置表单
 */
function resetForm() {
  Object.assign(form, {
    name: '',
    description: '',
    author: '',
    version: '1.0.0',
    category: '',
    tags: [],
    shareUrl: '',
    config: '',
    usage: ''
  })
  
  formRef.value?.clearValidate()
}

/**
 * 处理弹窗关闭
 */
async function handleClose() {
  // 检查表单是否有内容
  const hasContent = Object.values(form).some(value => {
    if (Array.isArray(value)) {
      return value.length > 0
    }
    return value !== '' && value !== '1.0.0'
  })
  
  if (hasContent) {
    try {
      await ElMessageBox.confirm(
        '表单中有未保存的内容，确定要关闭吗？',
        '确认关闭',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    } catch {
      return // 用户取消关闭
    }
  }
  
  // 执行退出动画
  await animateDialogExit('.register-dialog .el-dialog')
  
  // 关闭弹窗并重置表单
  visible.value = false
  resetForm()
}

/**
 * 处理表单提交
 */
async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    console.log('🔍 [RegisterDialog] 开始表单提交流程')
    console.log('🔍 [RegisterDialog] 原始表单数据:', JSON.stringify(form, null, 2))
    
    // 表单验证
    await formRef.value.validate()
    console.log('✅ [RegisterDialog] 表单验证通过')
    
    // 按钮点击动画
    animateButtonClick('.submit-btn')
    
    loading.value = true
    
    // 准备提交数据
    const submitData: CreateAgentInput = {
      ...form,
      tags: form.tags.filter(tag => tag.trim() !== '')
    }
    
    // 模拟提交延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    console.log('🚀 [RegisterDialog] 发送提交事件到父组件')
    // 根据模式发送不同的事件
    if (isEditMode.value) {
      emit('edit', { ...submitData, id: props.agent?.id })
    } else {
      emit('submit', submitData)
    }
    
    // 关闭弹窗
    visible.value = false
    resetForm()
    
  } catch (error) {
    console.error('❌ [RegisterDialog] 表单验证失败:', error)
    ElMessage.error('请检查表单内容')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/**
 * 注册弹窗样式 - 简洁科技风格
 * 采用暗色背景和浅色表单项设计
 */

/* Element Plus 组件样式现在由 global.scss 统一管理 */

/* 弹窗内容 */
.dialog-content {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
  background-color: #1a1a2e;
}

/* 表单区域 */
.register-form {
  color: #e0e6ed;
}

/* 表单分组 */
.form-section {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #0f1419;
  border: 1px solid rgba(50, 236, 138, 0.2);
  border-radius: 6px;
}

.section-title {
  color: #32ec8a;
  font-size: 14px;
  font-weight: 600;
  margin: 0 0 16px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(50, 236, 138, 0.3);
}

/* Element Plus 组件样式现在由 global.scss 统一管理 */

/* 弹窗底部 */
.dialog-footer {
  padding: 16px 20px;
  background-color: #16213e;
  border-top: 1px solid rgba(50, 236, 138, 0.3);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 取消按钮 */
.cancel-btn {
  background-color: transparent !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
  color: #e0e6ed !important;
  padding: 8px 16px;
  border-radius: 4px;
}

.cancel-btn:hover {
  border-color: #32ec8a !important;
  color: #32ec8a !important;
}

/* 提交按钮 */
.submit-btn {
  background-color: #32ec8a !important;
  border: 1px solid #32ec8a !important;
  color: #ffffff !important;
  padding: 8px 16px;
  border-radius: 4px;
}

.submit-btn:hover {
  background-color: #28c470 !important;
  border-color: #28c470 !important;
}

.submit-btn:disabled {
  background-color: rgba(50, 236, 138, 0.3) !important;
  border-color: rgba(50, 236, 138, 0.3) !important;
  color: rgba(255, 255, 255, 0.5) !important;
}

/* 滚动条 */
.dialog-content::-webkit-scrollbar {
  width: 4px;
}

.dialog-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
}

.dialog-content::-webkit-scrollbar-thumb {
  background: rgba(50, 236, 138, 0.5);
  border-radius: 2px;
}

/* 响应式 */
@media (max-width: 768px) {
  .dialog-content {
    padding: 16px;
  }
  
  .form-section {
    padding: 12px;
  }
}
</style>